﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using teacher.Util;
using System.Data;
using System.Collections;
using teacher.Models;
using Newtonsoft.Json;

namespace tearcher.Controllers
{
    public class UserController : Controller
    {
        //登录
        [AppAuthorizeAttribute(Users = "Login")]
        public string Login(String name, String pwd)
        {
            DataTable dt = DbHelper.ExecuteDataTable(string.Format("select * from t_teacher where phone='{0}' and password='{1}'", name, Helper.DESencrypt(pwd)));
            DataTable classes = null;
            if (dt.Rows.Count > 0)
            {
                if ("1".Equals(dt.Rows[0]["status"]))
                {
                    try
                    {
                        classes = DbHelper.ExecuteDataTable(string.Format("select classId from T_TeacherClassRelation where teacherId='{0}'", dt.Rows[0]["id"]));
                        DataTable dt_token = DbHelper.ExecuteDataTable(string.Format("select * from t_token where t_id='{0}'", dt.Rows[0]["id"]));
                        if (dt_token.Rows.Count > 0)
                        {
                            System.Web.HttpRuntime.Cache.Remove(dt_token.Rows[0]["token"].ToString());
                        }
                    }
                    catch
                    {
                    }
                    string token = System.Guid.NewGuid().ToString();
                    DbHelper.ExecuteNonQuery(string.Format("delete t_token where t_id='{0}'", dt.Rows[0]["id"]));
                    DbHelper.ExecuteNonQuery(string.Format("insert into t_token(t_id,token) values('{0}','{1}')", dt.Rows[0]["id"], token));
                    object authority = new
                    {
                        addNotice = true,
                        delNotice = true,
                        addNews = true,
                        delNews = true,
                        editNews = true,
                        addCourse = true,
                        delCourse = true,
                        editCourse = true,
                        addRecipe = true,
                        delRecipe = true,
                        editRecipe = true
                    };
                    DbHelper.ExecuteNonQuery(string.Format("insert into [T_LoginLog_teacher](id,loginUserId,loginTime,type) values('{0}','{1}',getdate(),'{2}')", System.Guid.NewGuid().ToString(), dt.Rows[0]["id"], "1"));
                    return Helper.sendOKJson(Request, new { token = token, phone = dt.Rows[0]["phone"], headimgURL = dt.Rows[0]["headimgURL"], teacherName = dt.Rows[0]["teacherName"], schoolId = dt.Rows[0]["schoolId"], id = dt.Rows[0]["id"], classes = classes, authority = authority });
                }
                else
                {
                    return Helper.sendErrorJson(Request, "该账号已经被禁用，请与管理员联系！");
                }
            }
            else
            {
                return Helper.sendErrorJson(Request, "用户名或是密码错误");
            }
        }

        //用户--修改头像
        [AppAuthorizeAttribute(Users = "updatePhoto")]
        public String updatePhoto(string url)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                DbHelper.ExecuteNonQuery(string.Format("update t_teacher set headimgURL='{0}' where id='{1}'", url, dt_token.Rows[0]["id"]));
                return Helper.sendOKJson(Request, null);
            }
            catch (Exception e)
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误");
            }
        }

        //用户--修改密码
        [AppAuthorizeAttribute(Users = "updatePwd")]
        public String updatePwd(string currentPwd, string newPwd)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                if (Helper.DESencrypt(currentPwd).Equals(dt_token.Rows[0]["password"]))
                {
                    DbHelper.ExecuteNonQuery(string.Format("update t_teacher set password='{0}' where id='{1}'", Helper.DESencrypt(newPwd), dt_token.Rows[0]["id"]));
                    return Helper.sendOKJson(Request, null);
                }
                else
                {
                    return Helper.sendErrorJson(Request, "当前密码不正确！");
                }

            }
            catch (Exception e)
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误");
            }
        }


        //获取个人信息
        [AppAuthorizeAttribute(Users = "getTeacherInfo")]
        public String getTeacherInfo()
        {
            Hashtable ht = new Hashtable();
            DataTable dt_token = Helper.getToken(Request);
            DataTable dt = DbHelper.ExecuteDataTable(string.Format("select *,convert(varchar(20),bornDay,120) as birthday from t_teacher where id='{0}'", dt_token.Rows[0]["id"]));
            return Helper.sendOKJson(Request, dt);
        }

        //用户 --登录日志
        public String loginLog(string token)
        {
            try
            {
                DataTable dt_token = DbHelper.ExecuteDataTable(string.Format("select * from t_token where token='{0}'", token));
                if (dt_token.Rows.Count > 0)
                {
                    DbHelper.ExecuteNonQuery(string.Format("insert into [T_LoginLog_teacher](id,loginUserId,loginTime,type) values('{0}','{1}',getdate(),'{2}')", System.Guid.NewGuid().ToString(), dt_token.Rows[0]["t_id"], "1"));
                }
                return Helper.sendOKJson(Request, null);
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //用户 --登录日志
        public String loginLog2(string userId)
        {
            try
            {
                if (!string.IsNullOrEmpty(userId))
                {
                    DbHelper.ExecuteNonQuery(string.Format("insert into [T_LoginLog_teacher](id,loginUserId,loginTime,type) values(NEWID(),'{0}',getdate(),'{1}')", userId, "1"));
                    return Helper.sendOKJson(Request, new { code = 1, msg = "登录日志成功" });
                }
                else
                {
                    return Helper.sendOKJson(Request, new { code = 0, msg = "userId不能为空" });
                }
            }
            catch
            {
                return Helper.sendErrorJson(Request, "记录登录日志出错！");
            }
        }

        //用户 --退出
        public String loginOut(string token)
        {
            try
            {
                DataTable dt_token = DbHelper.ExecuteDataTable(string.Format("select * from t_token where token='{0}'", token));
                if (dt_token.Rows.Count > 0)
                {
                    DbHelper.ExecuteNonQuery(string.Format("insert into [T_LoginLog_teacher](id,loginUserId,loginTime,type) values('{0}','{1}',getdate(),'{2}')", System.Guid.NewGuid().ToString(), dt_token.Rows[0]["t_id"], "2"));
                    System.Web.HttpRuntime.Cache.Remove(dt_token.Rows[0]["token"].ToString());
                }
                return Helper.sendOKJson(Request, null);
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        // 通知 -- 列表
        [AppAuthorizeAttribute(Users = "getNoticeList")]
        public String getNoticeList()
        {
            try
            {
                int pageSize = Convert.ToInt32(Request["pageSize"]);
                int pageNumber = Convert.ToInt32(Request["pageNumber"]);
                DataTable dt_token = Helper.getToken(Request);
                string condition = string.Format("and schoolid ='{0}'", dt_token.Rows[0]["schoolid"]);
                int count = DbHelper.ExecuteDataCount("T_Notification", "id", condition);
                DataTable dt = DbHelper.ExecuteDataTable("T_Notification", "title,contentWZ,source,coverImgURL,convert(varchar(23),creatTime,120) creatTime,id", "id", condition, "creatTime desc", pageNumber, pageSize);
                return Helper.sendOKJson(Request, new { count = count, list = dt, page = new Page(count, pageSize, pageNumber) });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //通知 -- 添加
        [AppAuthorizeAttribute(Users = "addNotice")]
        public String addNotice()
        {
            try
            {
                string classList = Convert.ToString(Request["classList"]);
                string title = Convert.ToString(Request["title"]);
                string content = Convert.ToString(Request["content"]);
                string coverImgURL = Convert.ToString(Request["coverImgURL"]);
                DataTable dt_token = Helper.getToken(Request);
                DataTable sch = DbHelper.ExecuteDataTable(string.Format("select schoolName from T_School where schoolid='{0}'", dt_token.Rows[0]["schoolid"]));
                DbHelper.ExecuteNonQuery(
                string.Format(@"insert into T_Notification(id,title,contentWZ,coverImgURL,creatTime,source,schoolid)
                values('{0}','{1}','{2}','{3}',getdate(),'{4}','{5}')",
                System.Guid.NewGuid().ToString(), title, content, coverImgURL, sch.Rows[0]["schoolName"], dt_token.Rows[0]["schoolid"]));
                Message mrs = null;
                try
                {
                    if (String.IsNullOrEmpty(classList) || "-1".Equals(classList))
                    {
                        DataTable classes = DbHelper.ExecuteDataTable(string.Format("select classid from T_TeacherClassRelation where teacherid='{0}'", dt_token.Rows[0]["id"]));
                        for (int i = 0; i < classes.Rows.Count; i++)
                        {
                            string data = "{\"title\":\"" + Helper.EncodeBase64(title) + "\",\"msg\":\"" + Helper.EncodeBase64(content) + "\",\"tag\":\"" + classes.Rows[i]["classid"] + "JiaZhang\"}";
                            data = Helper.EncodeBase64(data);
                            string getData = Helper.getWebServiceJson(Helper.webservicePath + "?method=TagsDevice&appType=1&pushType=1&data=" + data);
                            mrs = JsonConvert.DeserializeObject<Message>(getData);
                            //string data = "{\"title\":\"" + Helper.EncodeBase64(title) + "\",\"msg\":\"" + Helper.EncodeBase64(content) + "\",\"tag\":\"" + dt_token.Rows[0]["schoolid"] + "JiaZhang\"}";
                            //data = Helper.EncodeBase64(data);
                            //string getData = Helper.getWebServiceJson(Helper.webservicePath + "?method=TagsDevice&appType=1&pushType=1&data=" + data);
                            //mrs = JsonConvert.DeserializeObject<Message>(getData);
                        }
                    }
                    else
                    {
                        foreach (string id in classList.Split(','))
                        {
                            string data = "{\"title\":\"" + Helper.EncodeBase64(title) + "\",\"msg\":\"" + Helper.EncodeBase64(content) + "\",\"tag\":\"" + id + "JiaZhang\"}";
                            data = Helper.EncodeBase64(data);
                            string getData = Helper.getWebServiceJson(Helper.webservicePath + "?method=TagsDevice&appType=1&pushType=1&data=" + data);
                            mrs = JsonConvert.DeserializeObject<Message>(getData);
                        }
                    }
                }
                catch
                {
                    mrs = new Message();
                    mrs.code = "1";
                    mrs.msg = "推送通知消息失败！";
                }
                return Helper.sendOKJson(Request, new { mcode = mrs.code, mmsg = mrs.msg });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //通知 -- 删除
        [AppAuthorizeAttribute(Users = "delNotice")]
        public String delNotice(string id)
        {
            try
            {
                DbHelper.ExecuteNonQuery(string.Format("delete T_Notification where id='{0}'", id));
                return Helper.sendOKJson(Request, new { });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }


        //班级 -- 列表
        [AppAuthorizeAttribute(Users = "getClassList")]
        public String getClassList(string keyword)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string condition = string.Format("  and id in(select classid from T_TeacherClassRelation where teacherid='{0}')", dt_token.Rows[0]["id"]);
                if (!string.IsNullOrEmpty(keyword))
                {
                    condition += string.Format(" and className like '%{0}%'", keyword);
                }
                DataTable dt = DbHelper.ExecuteDataTable("T_Class", "*", "id", condition, "id asc", 1, 100);
                return Helper.sendOKJson(Request, new { list = dt });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //宝宝视频 -- 列表
        [AppAuthorizeAttribute(Users = "getVideoliveList")]
        public String getVideoliveList(string keyword)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string condition = string.Format(" and (a.classid in(select classid from T_TeacherClassRelation where teacherid='{0}')  or a.classid='ALL') and state=1", dt_token.Rows[0]["id"]);
                if (!string.IsNullOrEmpty(keyword))
                {
                    condition += string.Format(" and a.videoTitle like '%{0}%'", keyword);
                }
                string sql = string.Format("select  a.*,isnull(b.className,'其它') className,videoTitle from t_videolive a left join t_class b on a.classid=b.id where 1=1 {0}", condition);
                DataTable dt_video = DbHelper.ExecuteDataTable(sql);
                DataTable dt_class = DbHelper.ExecuteDataTable(string.Format("select className from t_class where id in (select classid from T_TeacherClassRelation where teacherid='{0}')", dt_token.Rows[0]["id"]));
                DataRow row = dt_class.NewRow();
                row["className"] = "其它";
                dt_class.Rows.Add(row);
                List<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < dt_class.Rows.Count; i++)
                {
                    List<Hashtable> v_list = new List<Hashtable>();
                    for (int j = 0; j < dt_video.Rows.Count; j++)
                    {
                        if (dt_class.Rows[i]["className"].ToString().Equals(dt_video.Rows[j]["className"].ToString()))
                        {
                            Hashtable v = new Hashtable();
                            v["coverImgURL"] = dt_video.Rows[j]["coverImgURL"];
                            v["videoTitle"] = dt_video.Rows[j]["videoTitle"];
                            v["deviceSerialNo"] = dt_video.Rows[j]["deviceSerialNo"];
                            v["videoURL"] = dt_video.Rows[j]["videoURL"];
                            v["id"] = dt_video.Rows[j]["id"];
                            v_list.Add(v);
                        }
                    }

                    if (v_list.Count > 0)
                    {
                        Hashtable ht = new Hashtable();
                        ht["className"] = dt_class.Rows[i]["className"];
                        ht["list"] = v_list;
                        list.Add(ht);
                    }
                }
                return Helper.sendOKJson(Request, new { list = list });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        // 互动留言 -- 班级列表
        [AppAuthorizeAttribute(Users = "getJiaoLiuList")]
        public String getJiaoLiuList(string keyword)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string sql = "";
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql = string.Format(@"select a.*,ISNULL(e.number,0) as number,ISNULL(e2.number,0) as number2 from t_class a left join(
                                        select classId,count(id) as number from t_jiaoliu a 
                                        inner join t_jiazhang b on a.sendpersonid=b.jzid
                                        inner join t_student c on b.stuId=c.studentId
                                        where a.readState=0 
                                        group by classId
                                        ) e on a.id=e.classid
                                        left join(
											select classId,isnull(count(studentid),0) as number from t_student where stuName like '%{0}%' group by classid
                                        ) e2 on e2.classid=a.id
                                        where id in(select classId from T_Student where stuName like '%{0}%' and a.id in(select classId from T_TeacherClassRelation where teacherId='{1}') )", keyword, dt_token.Rows[0]["id"]);
                }
                else
                {
                    sql = string.Format(@"select a.*,ISNULL(e.number,0) as number,ISNULL(e2.number,0) as number2 from t_class a left join(
                                        select classId,ISNULL(count(id),0)  as number from t_jiaoliu a 
                                        inner join t_jiazhang b on a.sendpersonid=b.jzid
                                        inner join t_student c on b.stuId=c.studentId
                                        where a.readState=0 
                                        group by classId
                                        ) e on a.id=e.classid
                                        left join(
											select classId,isnull(count(studentid),0) as number from t_student   group by classid
                                        ) e2 on e2.classid=a.id where a.id in(select classId from T_TeacherClassRelation where teacherId='{0}')", dt_token.Rows[0]["id"]);
                }
                DataTable dt = DbHelper.ExecuteDataTable(sql);
                return Helper.sendOKJson(Request, new { list = dt });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }


        //互动留言 -- 班级下面的用户列表
        [AppAuthorizeAttribute(Users = "getJiaoLiuList2")]
        public String getJiaoLiuList2(string classId)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string sql = string.Format(@"select isnull(a.stuName+'('+substring(e2.guanxi,1,1)+')',a.stuName) as stuName,a.headImgURL,ISNULL(number,0) as number,e2.jzid,studentid from t_student a left join(
                                        select jzid,stuid,count(id) as number from t_jiaoliu a 
                                        inner join t_jiazhang b on a.sendpersonid=b.jzid
                                        inner join t_student c on b.stuId=c.studentId
                                        where a.readState=0  and c.classid='{0}'
                                        group by jzid,stuid
                            ) e on a.studentid=e.stuId  inner join t_jiazhang e2 on e2.stuid=a.studentid where a.classid='{0}'", classId);

                DataTable dt = DbHelper.ExecuteDataTable(sql);
                return Helper.sendOKJson(Request, new { list = dt });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //互动留言 -- 交流信息
        [AppAuthorizeAttribute(Users = "getJiaoLiuList3")]
        public String getJiaoLiuList3(string jzid, string creatTime, int pageSize)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string condition = "";
                if (!string.IsNullOrEmpty(creatTime))
                {
                    condition = string.Format(" and creatTime<'{0}'", creatTime);
                }
                else
                {
                    DbHelper.ExecuteNonQuery(string.Format("update t_jiaoliu set readState=1 where sendPersonid='{0}' and readState=0", jzid));
                }
                string sql = string.Format(@"select top {2} a.words,b.jzName as name1,b.guanxi as gx1,b.headImgURL as img1,
                             c.teacherName as name2,c.headImgURL as img2,convert(varchar(20),creatTime,120) as creatTime
                              from t_jiaoliu a
                             left join t_jiazhang b on a.sendPersonid=b.jzid
                             left join t_teacher c on a.sendPersonid=c.id where (receivePersonId='{0}' or sendPersonid='{0}') {1} order by creatTime desc", jzid, condition, pageSize);


                DataTable dt = DbHelper.ExecuteDataTable(sql);
                return Helper.sendOKJson(Request, new { list = dt });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //互动留言 -- 交流信息
        [AppAuthorizeAttribute(Users = "getJiaoLiuList4")]
        public String getJiaoLiuList4(string jzid)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string condition = " and readState=0";
                string sql = string.Format(@"select  a.words,b.jzName as name1,b.guanxi as gx1,b.headImgURL as img1,
                             c.teacherName as name2,c.headImgURL as img2,convert(varchar(20),creatTime,120) as creatTime
                              from t_jiaoliu a
                             left join t_jiazhang b on a.sendPersonid=b.jzid
                             left join t_teacher c on a.sendPersonid=c.id where (sendPersonid='{0}') {1} order by creatTime asc", jzid, condition);

                DataTable dt = DbHelper.ExecuteDataTable(sql);
                DbHelper.ExecuteNonQuery(string.Format("update t_jiaoliu set readState=1 where sendPersonid='{0}' and readState=0", jzid));
                return Helper.sendOKJson(Request, new { list = dt });

            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //发送消息
        public String sendMsg(JiaoLiu jiaoliu, string receivePersonId)
        {
            try
            {

                DataTable dt_token = Helper.getToken(Request);
                string sql = string.Format(@"INSERT INTO [T_Jiaoliu]
                                           ([id]
                                           ,[words]
                                           ,[sendPersonId]
                                           ,[receivePersonId]
                                           ,[creatTime]
                                           ,[schoolId]
                                           ,[readState])
                                     VALUES
                                           ('{0}'
                                           ,'{1}'
                                           ,'{2}'
                                           ,'{3}'
                                           ,getdate()
                                           ,'{4}'
                                           ,0)", System.Guid.NewGuid().ToString(), jiaoliu.Words, dt_token.Rows[0]["id"], receivePersonId, dt_token.Rows[0]["schoolId"]);

                DbHelper.ExecuteNonQuery(sql);
                try
                {
                    string data = "{\"title\":\"" + Helper.EncodeBase64(dt_token.Rows[0]["teacherName"] + "老师给您留言") + "\",\"msg\":\"" + Helper.EncodeBase64(jiaoliu.Words) + "\",\"tag\":\"" + receivePersonId + "\"}";
                    data = Helper.EncodeBase64(data);
                    string getData = Helper.getWebServiceJson(Helper.webservicePath + "?method=SingleAccount&appType=1&pushType=1&data=" + data);
                    Message m = JsonConvert.DeserializeObject<Message>(getData);
                    if (m.code.Equals("0"))
                    {
                        Helper.WriteLog("推送消息失败:" + m.msg);
                    }
                }
                catch (Exception e)
                {
                    Helper.WriteLog("推送消息失败:" + e.Message);
                }
                return Helper.sendOKJson(Request, null);

            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }


        //新闻 -- 列表
        [AppAuthorizeAttribute(Users = "getNewsList")]
        public String getNewsList()
        {
            try
            {
                int pageSize = Convert.ToInt32(Request["pageSize"]);
                int pageNumber = Convert.ToInt32(Request["pageNumber"]);
                DataTable dt_token = Helper.getToken(Request);
                string condition = string.Format("and schoolid ='{0}'", dt_token.Rows[0]["schoolid"]);
                int count = DbHelper.ExecuteDataCount("T_SchoolNews", "id", condition);
                DataTable dt = DbHelper.ExecuteDataTable("T_SchoolNews", "title,contentWZ,source,headImgURL,convert(varchar(23),creatTime,120) creatTime,id", "id", condition, "creatTime desc", pageNumber, pageSize);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i]["contentWZ"] = Helper.stripHtml(dt.Rows[i]["contentWZ"].ToString());
                    if (dt.Rows[i]["contentWZ"].ToString().Length > 100)
                    {
                        dt.Rows[i]["contentWZ"] = dt.Rows[i]["contentWZ"].ToString().Substring(0, 100) + "...";
                    }
                }
                return Helper.sendOKJson(Request, new { count = count, list = dt, page = new Page(count, pageSize, pageNumber) });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //新闻 -- 明细
        [AppAuthorizeAttribute(Users = "getNewsDetail")]
        public String getNewsDetail(string id)
        {
            try
            {
                DataTable dt = DbHelper.ExecuteDataTable(string.Format("select * from t_schoolnews where id='{0}'", id));
                return Helper.sendOKJson(Request, new { contentWZ = dt.Rows[0]["contentWZ"], img = dt.Rows[0]["img"] });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        // 新闻 -- 添加
        [AppAuthorizeAttribute(Users = "addNews")]
        public string addNews()
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            try
            {
                string classList = Convert.ToString(Request["classList"]);
                string title = Convert.ToString(Request["title"]);
                string content = Convert.ToString(Request["content"]);
                string headImgURL = Convert.ToString(Request["headImgURL"]);
                string img = Convert.ToString(Request["img"]);
                DataTable dt_token = Helper.getToken(Request);
                DataTable sch = DbHelper.ExecuteDataTable(string.Format("select schoolName from T_School where schoolid='{0}'", dt_token.Rows[0]["schoolid"]));
                DbHelper.ExecuteNonQuery(
                string.Format(@"insert into T_SchoolNews(id,title,contentWZ,headImgURL,creatTime,source,schoolid,img)
                values('{0}','{1}','{2}','{3}',getdate(),'{4}','{5}','{6}')",
                System.Guid.NewGuid().ToString(), title, content, headImgURL, sch.Rows[0]["schoolName"], dt_token.Rows[0]["schoolid"], img));
                try
                {
                    string data = "{\"title\":\"" + Helper.EncodeBase64(title) + "\",\"msg\":\"" + Helper.EncodeBase64(content) + "\",\"tag\":\"" + dt_token.Rows[0]["schoolid"] + "JiaZhang\"}";
                    data = Helper.EncodeBase64(data);
                    string getData = Helper.getWebServiceJson(Helper.webservicePath + "?method=TagsDevice&appType=1&data=" + data);
                    Message mrs = JsonConvert.DeserializeObject<Message>(getData);
                    if (mrs.code.Equals("0"))
                    {
                        Helper.WriteLog("推送消息失败:" + mrs.msg);
                    }
                }
                catch (Exception ex)
                {
                    Helper.WriteLog("推送消息失败:" + ex.Message);
                }
                return Helper.sendOKJson(Request, null);
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //新闻 --- 删除
        [AppAuthorizeAttribute(Users = "delNews")]
        public String delNews(string id)
        {
            try
            {
                DbHelper.ExecuteNonQuery(string.Format("delete t_schoolnews where id='{0}'", id));
                return Helper.sendOKJson(Request, new { });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        // 新闻 -- 修改
        [AppAuthorizeAttribute(Users = "updateNews")]
        public string updateNews()
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            try
            {
                string id = Convert.ToString(Request["id"]);
                string classList = Convert.ToString(Request["classList"]);
                string title = Convert.ToString(Request["title"]);
                string content = Convert.ToString(Request["content"]);
                string headImgURL = Convert.ToString(Request["headImgURL"]);
                string img = Convert.ToString(Request["img"]);
                DataTable dt_token = Helper.getToken(Request);
                DbHelper.ExecuteNonQuery(
                string.Format(@"UPDATE [T_SchoolNews]
                               SET [title] = '{0}'
                                  ,[contentWZ] ='{1}'
                                  ,[headImgURL] = '{2}'
                                  ,[img] = '{3}'
                             WHERE id='{4}'", title, content, headImgURL, img, id));
                return Helper.sendOKJson(Request, new { });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //课程 -- 列表
        [AppAuthorizeAttribute(Users = "getCourseList")]
        public String getCourseList()
        {
            try
            {
                int pageSize = Convert.ToInt32(Request["pageSize"]);
                int pageNumber = Convert.ToInt32(Request["pageNumber"]);
                DataTable dt_token = Helper.getToken(Request);
                string condition = string.Format("and schoolid ='{0}'", dt_token.Rows[0]["schoolid"]);
                int count = DbHelper.ExecuteDataCount("T_Course", "id", condition);
                DataTable dt = DbHelper.ExecuteDataTable("T_Course", "datename(WEEKDAY, startDate) as weekDay, CONVERT(varchar(100), startDate, 23) as startDate,type,id,courseName", "id", condition, "startDate desc,type asc", pageNumber, pageSize);

                List<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool rs = true;
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (dt.Rows[i]["startDate"].ToString().Equals(list[j]["startDate"].ToString()))
                        {
                            rs = false;
                            break;
                        }
                    }
                    if (rs)
                    {
                        Hashtable ht = new Hashtable();
                        ht["startDate"] = dt.Rows[i]["startDate"];
                        ht["weekDay"] = dt.Rows[i]["weekDay"];
                        ht["courseName"] = dt.Rows[i]["courseName"];
                        list.Add(ht);
                    }
                }

                for (int i = 0; i < list.Count; i++)
                {
                    List<Hashtable> itemList = new List<Hashtable>();
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (dt.Rows[j]["startDate"].ToString().Equals(list[i]["startDate"].ToString()))
                        {
                            Hashtable ht = new Hashtable();
                            ht["type"] = dt.Rows[j]["type"];
                            ht["courseName"] = dt.Rows[j]["courseName"];
                            ht["id"] = dt.Rows[j]["id"];
                            itemList.Add(ht);
                        }
                    }
                    list[i]["itemList"] = itemList;
                }
                return Helper.sendOKJson(Request, new { count = count, list = list, page = new Page(count, pageSize, pageNumber) });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //课程 --- 删除
        [AppAuthorizeAttribute(Users = "delCourse")]
        public String delCourse(string startDate)
        {
            try
            {
                DbHelper.ExecuteNonQuery(string.Format("delete T_Course where startDate ='{0}'", startDate));
                return Helper.sendOKJson(Request, new { });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        // 课程 -- 添加
        [AppAuthorizeAttribute(Users = "addCourse")]
        public String addCourse(string courseName0, string courseName1, string startDate)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                int count = Convert.ToInt32(DbHelper.ExecuteDataTable(string.Format("select count(id) from T_Course where startDate='{0}' and schoolid='{1}'", startDate, dt_token.Rows[0]["schoolid"])).Rows[0][0]);
                if (count == 0)
                {
                    DbHelper.ExecuteNonQuery(string.Format(@"insert into T_Course(id,courseName,type,startDate,schoolid)
                         values('{0}','{1}','{2}','{3}','{4}')",
                    System.Guid.NewGuid().ToString(), courseName0, "上午", startDate, dt_token.Rows[0]["schoolid"]));
                    DbHelper.ExecuteNonQuery(string.Format(@"insert into T_Course(id,courseName,type,startDate,schoolid)
                         values('{0}','{1}','{2}','{3}','{4}')",
                    System.Guid.NewGuid().ToString(), courseName1, "下午", startDate, dt_token.Rows[0]["schoolid"]));
                    return Helper.sendOKJson(Request, new { });
                }
                else
                {
                    return Helper.sendErrorJson(Request, "已经有当天的课程！");
                }
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //课程 --- 修改
        [AppAuthorizeAttribute(Users = "updateCourse")]
        public String updateCourse(string courseName0, string courseName1, string startDate, string id0, string id1)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                int count = Convert.ToInt32(DbHelper.ExecuteDataTable(string.Format("select count(id) from T_Course where startDate='{0}' and id!='{1}' and id!='{2}' and schoolid='{3}'", startDate, id0, id1, dt_token.Rows[0]["schoolid"])).Rows[0][0]);
                if (count == 0)
                {
                    DbHelper.ExecuteNonQuery(string.Format(@"UPDATE [T_Course]
                               SET [startDate] = '{0}'
                                  ,[courseName] ='{1}'
                             WHERE id='{2}'", startDate, courseName0, id0));
                    DbHelper.ExecuteNonQuery(string.Format(@"UPDATE [T_Course]
                               SET [startDate] = '{0}'
                                  ,[courseName] ='{1}'
                             WHERE id='{2}'", startDate, courseName1, id1));
                    return Helper.sendOKJson(Request, new { });
                }
                else
                {
                    return Helper.sendErrorJson(Request, "已经有当天的课程！");
                }
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //食谱 -- 列表
        [AppAuthorizeAttribute(Users = "getRecipeList")]
        public String getRecipeList()
        {
            try
            {
                int pageSize = Convert.ToInt32(Request["pageSize"]);
                int pageNumber = Convert.ToInt32(Request["pageNumber"]);
                DataTable dt_token = Helper.getToken(Request);
                string condition = string.Format("and schoolid ='{0}'", dt_token.Rows[0]["schoolid"]);
                int count = DbHelper.ExecuteDataCount("T_Recipe", "id", condition);
                DataTable dt = DbHelper.ExecuteDataTable("T_Recipe as a", "datename(WEEKDAY, startDate) as weekDay, CONVERT(varchar(100), startDate, 23) as startDate,(select name from T_Dictionary where id=a.type) as type,id,footName,footImg", "id", condition, "startDate desc,type desc", pageNumber, pageSize);

                List<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool rs = true;
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (dt.Rows[i]["startDate"].ToString().Equals(list[j]["startDate"].ToString()))
                        {
                            rs = false;
                            break;
                        }
                    }
                    if (rs)
                    {
                        Hashtable ht = new Hashtable();
                        ht["startDate"] = dt.Rows[i]["startDate"];
                        ht["weekDay"] = dt.Rows[i]["weekDay"];
                        list.Add(ht);
                    }
                }

                for (int i = 0; i < list.Count; i++)
                {
                    List<Hashtable> itemList = new List<Hashtable>();
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (dt.Rows[j]["startDate"].ToString().Equals(list[i]["startDate"].ToString()))
                        {
                            Hashtable ht = new Hashtable();
                            ht["type"] = dt.Rows[j]["type"];
                            ht["footName"] = dt.Rows[j]["footName"];
                            ht["footImg"] = dt.Rows[j]["footImg"];
                            ht["id"] = dt.Rows[j]["id"];
                            itemList.Add(ht);
                        }
                    }
                    list[i]["itemList"] = itemList;
                }
                return Helper.sendOKJson(Request, new { count = count, list = list, page = new Page(count, pageSize, pageNumber) });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //食谱 --- 删除
        [AppAuthorizeAttribute(Users = "delRecipe")]
        public String delRecipe(string id)
        {
            try
            {
                DbHelper.ExecuteNonQuery(string.Format("delete T_Recipe where id='{0}'", id));
                return Helper.sendOKJson(Request, new { });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        // 餐谱 -- 添加
        [AppAuthorizeAttribute(Users = "addRecipe")]
        public String addRecipe(string footName, string footImg, string startDate, string type)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                int count = Convert.ToInt32(DbHelper.ExecuteDataTable(string.Format("select count(id) from T_Recipe where startDate='{0}' and type='{1}' and schoolid='{2}'", startDate, type, dt_token.Rows[0]["schoolid"])).Rows[0][0]);
                if (count == 0)
                {

                    if (!Helper.isInt(type))
                    {
                        DataTable dt_type = DbHelper.ExecuteDataTable(string.Format("select id from T_Dictionary where name='{0}'", type));
                        DbHelper.ExecuteNonQuery(string.Format(@"insert into T_Recipe(id,footName,footImg,type,startDate,schoolid)
                         values('{0}','{1}','{2}','{3}','{4}','{5}')",
                      System.Guid.NewGuid().ToString(), footName, footImg, dt_type.Rows[0]["id"], startDate, dt_token.Rows[0]["schoolid"]));
                    }
                    else
                    {
                        DbHelper.ExecuteNonQuery(string.Format(@"insert into T_Recipe(id,footName,footImg,type,startDate,schoolid)
                         values('{0}','{1}','{2}','{3}','{4}','{5}')",
                        System.Guid.NewGuid().ToString(), footName, footImg, type, startDate, dt_token.Rows[0]["schoolid"]));
                    }
                    return Helper.sendOKJson(Request, new { });
                }
                else
                {
                    return Helper.sendErrorJson(Request, "当天已经有此食谱！");
                }
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //食谱 --- 修改
        [AppAuthorizeAttribute(Users = "updateRecipe")]
        public String updateRecipe(string footName, string footImg, string startDate, string id, string type)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                int count = Convert.ToInt32(DbHelper.ExecuteDataTable(string.Format("select count(id) from T_Recipe where startDate='{0}' and type='{1}' and id!='{2}' and schoolid='{3}'", startDate, type, id, dt_token.Rows[0]["schoolid"])).Rows[0][0]);
                if (count == 0)
                {
                    if (!Helper.isInt(type))
                    {
                        DataTable dt_type = DbHelper.ExecuteDataTable(string.Format("select id from T_Dictionary where name='{0}'", type));
                        DbHelper.ExecuteNonQuery(string.Format(@"UPDATE [T_Recipe]
                               SET [startDate] = '{0}'
                                  ,[footName] ='{1}'
                                  ,[footImg] ='{2}'
                                  ,[type] ='{3}'
                             WHERE id='{4}'", startDate, footName, footImg, dt_type.Rows[0]["id"], id));
                    }
                    else
                    {

                        DbHelper.ExecuteNonQuery(string.Format(@"UPDATE [T_Recipe]
                               SET [startDate] = '{0}'
                                  ,[footName] ='{1}'
                                  ,[footImg] ='{2}'
                                  ,[type] ='{3}'
                             WHERE id='{4}'", startDate, footName, footImg, type, id));
                    }
                    return Helper.sendOKJson(Request, new { });
                }
                else
                {
                    return Helper.sendErrorJson(Request, "已经有当天的课程！");
                }
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //档案 -- 列表
        [AppAuthorizeAttribute(Users = "getGrowList")]
        public String getGrowList()
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                int pageSize = Convert.ToInt32(Request["pageSize"]);
                int pageNumber = Convert.ToInt32(Request["pageNumber"]);
                string userId = Request["userId"] == null ? "" : Convert.ToString(Request["userId"]);
                string schoolid = dt_token.Rows[0]["schoolid"].ToString();
                Hashtable ht = DbHelper.ExecuteDataProc(dt_token.Rows[0]["id"].ToString(), schoolid, pageSize, pageNumber);

                return Helper.sendOKJson(Request, new { count = ht["count"], list = ht["list"], page = new Page(Convert.ToInt32(ht["count"]), pageSize, pageNumber) });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //档案 -- 列表
        public String getGrowList2(string jzServerAddress, string teacherServerAddress, string schoolId, string userId)
        {
            try
            {
                int pageSize = Convert.ToInt32(Request["pageSize"]);
                int pageNumber = Convert.ToInt32(Request["pageNumber"]);              
                Hashtable ht = DbHelper.ExecuteDataProc2(userId, schoolId, pageSize, pageNumber, jzServerAddress, teacherServerAddress);
                return Helper.sendOKJson(Request, new { count = ht["count"], list = ht["list"], page = new Page(Convert.ToInt32(ht["count"]), pageSize, pageNumber) });
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理异常！");
            }
        }

        //档案 --评论
        public String pinglun(JiaoLiu jiaoliu, string growId)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string sql = string.Format(@"INSERT INTO [T_PingLunDangAn]
                                           ([id]
                                           ,[words]
                                           ,[userId]
                                           ,[growId]
                                           ,[creatTime])
                                     VALUES
                                           ('{0}'
                                           ,'{1}'
                                           ,'{2}'
                                           ,'{3}'
                                           ,getdate())", System.Guid.NewGuid().ToString(), jiaoliu.Words, dt_token.Rows[0]["id"], growId);

                DbHelper.ExecuteNonQuery(sql);
                return Helper.sendOKJson(Request, new { name = dt_token.Rows[0]["teacherName"], words = jiaoliu.Words, timeTxt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });

            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //档案 --赞
        public String dianZan(string growId)
        {
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                //取消
                if (Convert.ToInt32(DbHelper.ExecuteDataTable(string.Format("select COUNT(id) from T_Zan where zanUserId='{0}' and zanGrowId='{1}'", dt_token.Rows[0]["id"], growId)).Rows[0][0].ToString()) > 0)
                {
                    DbHelper.ExecuteNonQuery(string.Format("delete T_Zan where zanUserId='{0}' and zanGrowid='{1}'", dt_token.Rows[0]["id"], growId));
                    return Helper.sendOKJson(Request, new { name = dt_token.Rows[0]["teacherName"], type = 0 });
                }
                //添加
                else
                {
                    string sql = string.Format(@"INSERT INTO [T_Zan]
                                           ([id]
                                           ,[zanGrowId]
                                           ,[zanUserId])
                                     VALUES
                                           ('{0}'
                                           ,'{1}'
                                           ,'{2}')", System.Guid.NewGuid().ToString(), growId, dt_token.Rows[0]["id"]);
                    DbHelper.ExecuteNonQuery(sql);
                    return Helper.sendOKJson(Request, new { name = dt_token.Rows[0]["teacherName"], type = 1 });
                }
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        //档案 --添加
        [AppAuthorizeAttribute(Users = "addGrow")]
        public String addGrow(string words, string imgs)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            try
            {
                DataTable dt_token = Helper.getToken(Request);
                string masterid = System.Guid.NewGuid().ToString();
                string sql = string.Format(@"INSERT INTO [T_Grow]
                                           ([id]
                                           ,[userid]
                                           ,[words]
                                           ,[creatTime]
                                           ,[schoolid]
                                           ,[status]
                                            )
                                     VALUES
                                           ('{0}'
                                           ,'{1}'
                                           ,'{2}'
                                           ,getdate()
                                           ,'{3}'
                                           ,'1')", masterid, dt_token.Rows[0]["id"], words, dt_token.Rows[0]["schoolid"]);
                DbHelper.ExecuteDataTable(sql);
                string[] _imgs = imgs.Split(',');
                foreach (string img in _imgs)
                {
                    if (!string.IsNullOrEmpty(img))
                    {
                        string _sql = string.Format(@"INSERT INTO [T_growImgList]
                                           ([id]
                                           ,[masterid]
                                           ,[imgURL]
                                           ,[creatTime])
                                     VALUES
                                           ('{0}'
                                           ,'{1}'
                                           ,'{2}'
                                           ,getdate())", System.Guid.NewGuid().ToString(), masterid, img);
                        DbHelper.ExecuteNonQuery(_sql);
                    }
                }
                return Helper.sendOKJson(Request, null);
            }
            catch
            {
                return Helper.sendErrorJson(Request, "数据处理过程中发生错误！");
            }
        }

        public void test()
        {
            try
            {
                string data = "{\"title\":\"" + Helper.EncodeBase64("测试") + "\",\"msg\":\"" + Helper.EncodeBase64("测试内容") + "\"}";
                data = Helper.EncodeBase64(data);
                string getData = Helper.getWebServiceJson(Helper.webservicePath + "?method=PushAll&appType=1&pushType=1&data=" + data);
                Message m = JsonConvert.DeserializeObject<Message>(getData);
                if (m.code.Equals("1"))
                {
                    Helper.WriteLog("推送消息失败:" + m.msg);
                }
            }
            catch (Exception e)
            {
                Helper.WriteLog("推送消息失败:" + e.Message);
            }
        }
    }
}
